using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using UwinEducation.Domain.Entities;
using UwinEducation.Shared;

namespace UwinEducation.Infrastructure.Persistence;

public class DbInitializer
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger<DbInitializer> _logger;

    public DbInitializer(
        IServiceProvider serviceProvider,
        ILogger<DbInitializer> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }



    public async Task InitializeAsync()
    {
        try
        {
            using var scope = _serviceProvider.CreateScope();
            var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            var passwordHasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();

            // 确保数据库存在并创建
            _logger.LogInformation("开始创建数据库...");
            await context.Database.EnsureDeletedAsync();
            await context.Database.EnsureCreatedAsync();
            context.DropAllForeignKeys(); 
            _logger.LogInformation("数据库创建完成");

            // 初始化权限
            if (!await context.Permissions.AnyAsync())
            {
                _logger.LogInformation("开始初始化权限数据...");
                var permissions = new List<Permission>
                {
                    Permission.Create("课程日历", "calendar", "课程日历权限"),

                    Permission.Create("教师管理", "teacher", "教师管理权限"),
                    Permission.Create("教师课程", "teacher.course", "教师课程权限"),
                    Permission.Create("教师薪资", "teacher.salary", "教师薪资权限"),

                    Permission.Create("学生管理", "student", "学生管理权限"),
                    Permission.Create("学生课程", "student.course", "学生课程权限"),
                    Permission.Create("学生订单", "student.order", "学生订单权限"),
                    Permission.Create("课程明细", "student.course.details", "课程明细权限"),
                    Permission.Create("删除订单", "student.order.del", "删除订单权限"),
                    Permission.Create("订单审核", "order.examine", "订单审核权限"),


                    Permission.Create("基础数据", "basic", "基础数据权限"),
                    Permission.Create("教室管理", "basic.classroom", "教室管理权限"),
                    Permission.Create("课程管理", "basic.course", "课程管理权限"),
                    Permission.Create("学期管理", "basic.term", "学期管理权限"),
                    Permission.Create("描述管理", "basic.description", "描述管理权限"),

                    Permission.Create("系统管理", "system", "系统管理权限"),
                    Permission.Create("用户管理", "system.account", "用户管理权限"),
                    Permission.Create("角色管理", "system.role", "角色管理权限"),
                    Permission.Create("系统配置", "system.config", "系统配置权限"),

                };

                await context.Permissions.AddRangeAsync(permissions);
                await context.SaveChangesAsync();
                _logger.LogInformation("权限数据初始化完成");

                // 初始化角色
                _logger.LogInformation("开始初始化角色数据...");
                var adminRole = Role.Create("超级管理员", "系统超级管理员");
                var userRole = Role.Create("普通用户", "系统普通用户");

                await context.Roles.AddRangeAsync(new[] { adminRole, userRole });
                await context.SaveChangesAsync();

                // 为角色分配权限
                var rolePermissions = new List<RolePermission>();
                var allPermissions = await context.Permissions.ToListAsync();
                
                // 为超级管理员分配所有权限
                foreach (var permission in allPermissions)
                {
                    rolePermissions.Add(RolePermission.Create(adminRole.Id, permission.Id, permission.Code));
                }

                // 为普通用户分配基本权限
                foreach (var permission in allPermissions)
                {
                    if (permission.Code == "system" || permission.Code == "system.account" || permission.Code == "system.role")
                        continue;
                    rolePermissions.Add(RolePermission.Create(userRole.Id, permission.Id, permission.Code));
                }

                await context.RolePermissions.AddRangeAsync(rolePermissions);
                await context.SaveChangesAsync();
                _logger.LogInformation("角色数据初始化完成");

                // 初始化管理员用户
                if (!await context.Users.AnyAsync())
                {
                    _logger.LogInformation("开始初始化管理员用户...");
                    var adminUser = User.Create("admin", "超级管理员", "","", passwordHasher.HashPassword("admin123"));
                    await context.Users.AddAsync(adminUser);
                    await context.SaveChangesAsync();

                    var userRole1 = UserRole.Create(adminUser.Id, adminRole.Id);
                    await context.UserRoles.AddAsync(userRole1);
                    await context.SaveChangesAsync();
                    _logger.LogInformation("管理员用户初始化完成");
                }


                _logger.LogInformation("数据库初始化完成");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "数据库初始化失败");
            throw;
        }
    }
} 